#include <iostream>
#include <cstring>
#include <ctime>
#include <winsock2.h> // Windows下使用

#pragma comment(lib, "ws2_32.lib") // 链接Winsock库

// NTP时间戳转换为time_t
time_t ntpToTimeT(const unsigned char* ntpTime) {
    uint32_t seconds = ntohl(*(uint32_t*)(ntpTime + 4));
    return (time_t)(seconds - 2208988800U); // NTP起始时间1900-1-1到1970-1-1的秒数差
}

int main(int argc, char *argv[]) {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData); // 初始化Winsock

    SOCKET sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(123); // NTP端口

    bind(sockfd, (sockaddr*)&servaddr, sizeof(servaddr));

    char buffer[48] = {0}; // NTP消息长度
    sockaddr_in cliaddr;
    int len = sizeof(cliaddr);

    // 假设命令行参数已正确传递
    struct tm tmTime = {};
    strptime(argv[1], "%Y-%m-%d %H:%M:%S", &tmTime); // 解析时间字符串
    time_t timeSinceEpoch = mktime(&tmTime);
    unsigned char ntpTime[8] = {0};
    memcpy(ntpTime + 4, &timeSinceEpoch, 4); // 简化处理，忽略实际NTP格式

    while(true) {
        int n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (sockaddr*)&cliaddr, &len);
        if(n >= 48) {
            sendto(sockfd, (const char*)ntpTime, 48, 0, (sockaddr*)&cliaddr, len); // 发送NTP响应
        }
    }

    closesocket(sockfd);
    WSACleanup();
    return 0;
}